<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="机构编号" prop="mechanismCode">
        <el-input
          v-model="queryParams.mechanismCode"
          placeholder="请输入机构编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="机构名称" prop="mechanismName">
        <el-input
          v-model="queryParams.mechanismName"
          placeholder="请输入机构名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:mechanism:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
          >展开/折叠</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="mechanismList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="机构名称" prop="mechanismName" />
      <el-table-column label="机构编号" align="center" prop="mechanismCode" />
      <el-table-column label="机构级别" align="center" prop="levelId">
        <template slot-scope="scope">
          <span
            v-if="scope.row.levelId == item.roleId"
            v-for="item in roleList"
            :key="item.roleId"
          >
            {{ item.roleName }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="所在地区" align="center" prop="region" />
      <el-table-column label="机构联系电话" align="center" prop="tel" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:mechanism:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:mechanism:add']"
            >新增</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:mechanism:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="look(scope.row.id)"
          >查看员工</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改机构信息管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="机构名称" prop="mechanismName">
          <el-input v-model="form.mechanismName" placeholder="请输入机构名称" />
        </el-form-item>
        <el-form-item label="上级机构" prop="parentId">
          <treeselect
            v-model="form.parentId"
            :options="mechanismOptions"
            :normalizer="normalizer"
            placeholder="请选择上级机构id"
          />
        </el-form-item>
        <el-form-item label="机构级别" prop="levelId">
          <el-select
            v-model="form.levelId"
            placeholder="请选择下拉选择机构级别"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in roleList"
              :key="index"
              :label="item.roleName"
              :value="item.roleId"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <el-cascader
            ref="cascader"
            :options="areaSelectData"
            @change="handleChange"
            class="full-width"
            size="large"
            v-model="selectedOptions"
            placeholder="请选择所在地区"
            :disabled="form.id != null"
          />
        </el-form-item>
        <el-form-item label="电话号码" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入机构联系电话" />
        </el-form-item>
        <el-form-item label="机构编号" prop="mechanismCode">
          <el-input
            :disabled="true"
            v-model="form.mechanismCode"
            placeholder="选择地区后自动获取"
          />
        </el-form-item>
        <el-form-item label="登陆密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入登陆密码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMechanism,
  getMechanism,
  delMechanism,
  addMechanism,
  updateMechanism,
  selectMaxId,
} from "@/api/system/mechanism";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { regionData, codeToText } from "element-china-area-data";
import { getRoleList } from "@/api/system/role";

export default {
  name: "Mechanism",
  components: {
    Treeselect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 机构信息管理表格数据
      mechanismList: [],
      // 机构级别管理表格数据
      roleList: [],
      // 机构信息管理树选项
      mechanismOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        mechanismCode: null,
        mechanismName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        mechanismCode: [
          { required: true, message: "机构编号不能为空", trigger: "blur" },
        ],
        region: [
          { required: true, message: "所在地区不能为空", trigger: "blur" },
        ],
        mechanismName: [
          { required: true, message: "机构名称不能为空", trigger: "blur" },
        ],
      },
      areaSelectData: regionData, //省市区三级联动数据
      selectedOptions: [],
    };
  },
  created() {
    this.getList();
    this.getRoleList();
  },
  methods: {
    /** 查看员工*/
    look(id){
      this.$router.push("/mechanism/user/list/"+id);
    },

    /** 查询机构信息管理列表 */
    getList() {
      this.loading = true;
      listMechanism(this.queryParams).then((response) => {
        this.mechanismList = this.handleTree(response.data, "id", "parentId");
        this.loading = false;
      });
    },
    /** 查询机构级别信息列表 */
    getRoleList() {
      this.loading = true;
      getRoleList(null).then((response) => {
        this.roleList = response.data;
        this.loading = false;
      });
    },
    /** 转换机构信息管理数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.mechanismName,
        children: node.children,
      };
    },
    /** 查询机构信息管理下拉树结构 */
    getTreeselect() {
      listMechanism().then((response) => {
        this.mechanismOptions = [];
        const data = { id: 0, mechanismName: "顶级节点", children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.mechanismOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        mechanismCode: null,
        mechanismName: null,
        levelId: null,
        addvcd: null,
        password: null,
        tel: null,
        parentId: null,
        createTime: null,
        isDeleted: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.selectedOptions = [];
      this.open = true;
      this.title = "添加机构信息管理";
    },
    /**省市区三级联动 */
    handleChange(value) {
      //value为省市区code数组M
      if (value) {
        selectMaxId().then((maxId) => {
          this.form.mechanismCode =
            "M" + value[2] + String(maxId + 1).padStart(5, "0");
        });
        this.form.addvcd = value[2];
        this.form.region =
          codeToText[value[0]] +
          "-" +
          codeToText[value[1]] +
          "-" +
          codeToText[value[2]];
      }
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.id;
      }
      getMechanism(row.id).then((response) => {
        this.form = response.data;
        this.selectedOptions = response.data.cityCode;
        this.open = true;
        this.title = "修改机构信息管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateMechanism(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMechanism(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除机构信息管理编号为"' + row.id + '"的数据项？')
        .then(function () {
          return delMechanism(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
